/**
 * New node file
 */

var key = "ab@#$%*rrpkg,l;x";
var timeWide = (1000 * 60 * 30);
var timeExpiredFactor = 2;
var genTok = {};

var crypto = require('crypto');

function getTimeStamp() {
	"use strict";
	var timestamp = Math.floor(Date.now() / timeWide);
	return timestamp;
}

genTok.gen = function gen(account) {
	"use strict";

	var timeStamp = getTimeStamp();

	var cipher = crypto.createCipher('aes-256-cbc', key);

	var encryptedPassword = cipher.update(account + "|" + timeStamp, 'utf8',
			'base64');
	encryptedPassword += cipher.final('base64');

	return encryptedPassword;
};

function checkExpired(timestamp) {
	"use strict";
	var current = Math.floor(Date.now() / timeWide);
	if (current - timestamp >= timeExpiredFactor) {
		return true;
	}

	return false;
}

genTok.parse = function parse(token) {
	"use strict";

	try {
		var decipher = crypto.createDecipher('aes-256-cbc', key);
		var decryptedPassword = decipher.update(token, 'base64', 'utf8');
		decryptedPassword += decipher.final('utf8');

		var mixeds = decryptedPassword.split("|");
		var account = mixeds[0];
		var timestamp = mixeds[1];

		var isExpired = checkExpired(timestamp);

		return {
			"account" : account,
			expired : isExpired
		};
	} catch (err) {
		console.error(err);
	}

	return null;
};

module.exports = genTok;
